import 'package:flutter_module/common/base/page/BasePage.dart';
import 'package:flutter_module/common/widgets/CommonWidget.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_boost/flutter_boost.dart';
import 'package:get/get.dart';
import '../../../res/colors.dart';
import '../logic/BasicLogic.dart';

///BasicPage 基类, 抽取渲染页面公共部分
abstract class BasicPage<Page extends BasePage, T extends BasicLogic>
    extends BaseState<Page> {
  @override
  Widget build(BuildContext context) {
    return YouthToolBar(
      body: body(context),
      resizeToAvoidBottomInset: resizeToAvoidBottomInset(),
      needAppBar: isNeedAppBar(),
      ifNeedScaffold: ifNeedScaffold(),
      myAppBar: appbar(),
      titleBar: header(),
      title: screenName(),
      actions: actions(),
      extendBodyBehindAppBar: extendBodyBehindAppBar(),
      bodyColor: bodyColor(),
      onPressed: () => onPressed(),
    );
  }

  ///NOTE: 生命周期
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    _closeGetXController();
    _closeGetXControllers();
    super.dispose();
  }

  ///在 didChangeAppLifecycleState 接收生命周期的变化
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.paused) {
      // 离开页面
      //关闭键盘
      hideKeyboard(context);
    }
    if (state == AppLifecycleState.resumed) {
      // 重新显示界面
    }
  }

  ///NOTE: 需要基类统一处理的地方
  ///全局点击空白处关闭键盘手势
  void hideKeyboard(BuildContext context) {
    FocusScopeNode currentFocus = FocusScope.of(context);
    if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
      FocusManager.instance.primaryFocus?.unfocus();
    }
  }

  ///解决控制器销毁问题
  ///Close GetxController bound to the current page
  void _closeGetXController() {
    if (widget.bind == null) {
      GetInstance().delete(key: Get.find<T>().runtimeType.toString());
      return;
    }

    var key = widget.bind.runtimeType.toString() + (widget.tag ?? '');
    GetInstance().delete(key: key);
  }

  ///Batch close GetxController bound to the current page
  void _closeGetXControllers() {
    if (widget.binds == null) {
      return;
    }

    for (var i = 0; i < widget.binds!.length; i++) {
      var type = widget.binds![i].runtimeType.toString();

      if (widget.tags == null) {
        GetInstance().delete(key: type);
      } else {
        var key = type + (widget.tags?[i] ?? '');
        GetInstance().delete(key: key);
      }
    }
  }

  ///NOTE: 这里没有在基类中初始化是因为渲染wedget 尽量写在子组件state中, 更好的状态管理,更好的性能
  ///body()子类必须实现
  Widget body(BuildContext context);

  ///当前页面的 logic 控制器
  T get currentLogic;

  ///NOTE: 可选实现

  ///容器背景颜色，子类可选实现
  Color containerBgColor() => YouthColors.color_F8F7F7;

  ///scaffold背景颜色，子类可选实现
  Color scaffoldBackgroundColor() => YouthColors.color_F8F7F7;

  /// 返回事件，子类可选实现
  void onPressed() {
    BoostNavigator.instance.pop();
  }

  /// 安卓导航栏变白问题，子类可选实现
  SystemUiOverlayStyle systemStatusBarUi() => const SystemUiOverlayStyle(
        statusBarColor: Colors.transparent,
        statusBarIconBrightness: Brightness.dark,
        statusBarBrightness: Brightness.dark,
      );

  ///自定义导航栏视图，子类可选实现
  Widget? header() => null;

  ///自定义导航栏，子类可选实现
  PreferredSizeWidget? appbar() => null;

  /// 导航栏右侧视图，子类可选实现
  List<Widget>? actions() => null;

  ///禁止软键盘弹出导致布局rebuild true（重绘） false 不重绘，子类可选实现
  bool resizeToAvoidBottomInset() => false;

  bool isNeedAppBar() => true;

  bool extendBodyBehindAppBar() => false;

  Color bodyColor() => YouthColors.color_F8F7F7;

  ///是否需要全屏（如果不全屏的时候，隐藏导航栏会遮挡该区域的手势，需要设置该属性为false去掉Scaffold）
  bool ifNeedScaffold() => true;
}
